/*
 * This file is part of "Sorting Thoughts" project.
 *
 * Copyright (c) 2009 Hendrik Ebel
 * All Rights Reserved.
 *
 * Please visit http://code.google.com/p/sorting-thoughts/ for more information.
 *
 * --LICENSE NOTICE--
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; If not, see <http://www.gnu.org/licenses/>.
 * --LICENSE NOTICE--
 */
function EditAssistant(thought, isNew){
    this.selectedThought = thought;
    this.isNew = isNew;
}

EditAssistant.prototype.setup = function(){
	Mojo.Log.info("#######################################");
	Mojo.Log.info("Edit setup");
	Mojo.Log.info("#######################################")
	if (!this.isNew) {
		this.controller.setInitialFocusedElement('editThoughtContent');
		this.controller.modelChanged(this.thoughtContentModel, this);
	}
    this.selectThought();
	
    
    if (this.isNew) {
        this.titleAttributes = {
            hintText: $L('Enter a Title'),
            multiline: false,
            enterSubmits: true,
            autoFocus: true
        }
        
        this.contentAttributes = {
        }
    } else {
        this.titleAttributes = {
            multiline: false,
            enterSubmits: true
        }
        
        this.contentAttributes = {
        }
    }
    
    this.controller.setupWidget("editThoughtTitle", this.titleAttributes, this.thoughtTitleModel = {
        value: "",
        disable: false
    });
    
    this.controller.setupWidget("editThoughtContent", this.contentAttributes, this.thoughtContentModel = {
        value: "",
        disable: false
    });
    
    // add command menu
	if (SortingThoughts.isTouchPad()) {
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, {
			items: [{
				label: 'Back',
				command: 'backToOverview',
				icon: 'back'
			}, {
				items: [{
					label: 'Save',
					command: 'saveThought',
					icon: 'save'
				}, {
					label: 'Email',
					command: 'mailThought',
					iconPath: 'images/menu-icon-compose.png'
				}]
			}]
		});
	} else {
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, {
			items: [{
				label: 'Email',
				command: 'mailThought',
				iconPath: 'images/menu-icon-compose.png'
			}]
		});
	}
	
    // Setup App Menu 
	Mojo.Log.info("setup app menu");
    this.controller.setupWidget(Mojo.Menu.appMenu, SortingThoughts.MenuAttrForRichText, SortingThoughts.MenuModelEditView);
	
	// handle app minimizing
	this.minimizeApp = this.minimizeAppHandler.bind(this);
	// handle focus of content
	this.contentFocus = this.handleContentFocusHandler.bind(this);
};

EditAssistant.prototype.activate = function(event) {
	Mojo.Log.info("#######################################");
	Mojo.Log.info("Edit activate");
	Mojo.Log.info("#######################################");
	
	this.controller.listen(this.controller.document, Mojo.Event.stageDeactivate, this.minimizeApp);
//	this.controller.listen(this.controller.get("editThoughtContent"), "focus", this.contentFocus);
	
	// check orientation
	var appController = Mojo.Controller.getAppController();
	var orientation = appController.getScreenOrientation();
	
	if (SortingThoughts.isTouchPad()) {
		this.setThoughtInfo(orientation);
		this.orientationChanged(orientation);
	} else {
		if(orientation == 'right' || orientation == 'left') {
			this.orientationChanged(orientation);
		} else {
			this.setThoughtInfo(orientation);
		}
	}
	
};

EditAssistant.prototype.deactivate = function(event) {
	Mojo.Log.info("#######################################");
	Mojo.Log.info("Edit deactivate");
	Mojo.Log.info("#######################################");
	this.updateThought();
	this.controller.stopListening(this.controller.document, Mojo.Event.stageDeactivate, this.minimizeApp);
//	this.controller.stopListening(this.controller.get("editThoughtContent"), "focus", this.contentFocus);
};

EditAssistant.prototype.cleanup = function(event) {
	Mojo.Log.info("#######################################");
	Mojo.Log.info("Edit cleanup");
	Mojo.Log.info("#######################################");
};

/*
 * Update thought if app minimized
 */
EditAssistant.prototype.minimizeAppHandler = function() {
	Mojo.Log.info("App is minimized!");
	$('editThoughtTitle').mojo.blur();
	this.updateThought();
};

EditAssistant.prototype.handleContentFocusHandler = function() {
	Mojo.Log.info("Content focused!");
	var richTextField = this.controller.get('editThoughtContent');
//	var endPos = richTextField.innerHTML.length;
//	richTextField.innerHTML = richTextField.innerHTML;
//	this.controller.modelChanged(this.thoughtContentModel, this);
//	Mojo.Log.info("Pos: " + endPos);
//	richTextField.mojo.setCursorPosition(endPos, endPos);

	this.controller.get('editThoughtContent').innerHTML = richTextField.innerHTML;
    this.controller.modelChanged(this.thoughtContentModel, this);
};

/*
 * Set additional thought info like create and view date.
 */
EditAssistant.prototype.setThoughtInfo = function(orientation) {
	this.controller.get('created').innerHTML = $L("Created: ");
    this.controller.get('modified').innerHTML = $L("Modified: ");
    this.controller.get('lastViewed').innerHTML = $L("Last Viewed: ");
	
	var cDate = this.selectedThought.createDateText;
	var mDate = this.selectedThought.modifiedDateText;
	var vDate = this.selectedThought.lastViewDateText;
	var sDate = this.selectedThought.lastSyncDateText;
	
	Mojo.Log.info("info data updated for orientation: " + orientation);
	// full date format only in landscape view and not for pixi device
	if (SortingThoughts.isTouchPad() || ((orientation == 'right' || orientation == 'left') && Mojo.Environment.DeviceInfo.touchableRows >= 8)) {
		cDate = this.selectedThought.longCreateDateText;
	    mDate = this.selectedThought.longModifiedDateText;
		vDate = this.selectedThought.longLastViewDateText;
		sDate = this.selectedThought.longLastSyncDateText;
	} 
	
	this.controller.get('createdValue').innerHTML = cDate;
	this.controller.get('modifiedValue').innerHTML = mDate;
	this.controller.get('lastViewedValue').innerHTML = vDate;
	
	if (this.selectedThought.lastSyncDateText != null && this.selectedThought.lastSyncDateText.length > 0) {
		this.controller.get('lastSync').innerHTML = $L("Last Sync") + ": ";
		this.controller.get('lastSyncValue').innerHTML = sDate;
	}
	Mojo.Log.info("info data updated");
};

EditAssistant.prototype.handleCommand = function(event){
    if (event.type == Mojo.Event.command) {
        switch (event.command) {
            case 'mailThought':
				$('editThoughtTitle').mojo.blur();
                this.controller.serviceRequest('palm://com.palm.applicationManager', {
                    method: 'launch',
                    parameters: {
                        id: 'com.palm.app.email',
                        params: {
                            summary: this.thoughtTitleModel.value,
                            text: $('editThoughtContent').innerHTML
                        }
                    }
                });
                break;
			case 'saveThought':
				this.updateThought();
				break;
			case 'backToOverview':
				this.updateThought();
				event.stopPropagation();
				this.controller.stageController.popScene();
				break;
        }
    }
};

/*
 * Handle orientation changes.
 */
EditAssistant.prototype.orientationChanged = function(orientation) {
	
	if (SortingThoughts.isTouchPad()) {
		$('editTitleDiv').removeClassName("editTitle");
		$('editTitleDiv').addClassName("editTitleTouchpadWide");
		
		$('editContentDiv').removeClassName("editContent");
		$('editContentDiv').addClassName("editContentTouchpadWide");
		
		$('infoWrapperDiv').removeClassName("infoWrapper");
		$('infoWrapperDiv').addClassName("infoWrapperTouchpadWide");
		
		$('footerDiv').removeClassName("footer");
		$('footerDiv').addClassName("footerTouchpadWide");
	} else {
		var editTitleStyleWide = "editTitleWide";
		var editContentStyleWide = "editContentWide";
		var infoWrapperStyleWide =  "infoWrapperWide";
		var footerStyleWide =  "footerWide";
		
		// set special pixi style 
		if(Mojo.Environment.DeviceInfo.touchableRows < 8) {
		   editTitleStyleWide = "editTitleWidePixi";
		   editContentStyleWide = "editContentWidePixi";
		   infoWrapperStyleWide =  "infoWrapperWidePixi";
		   footerStyleWide =  "footerWidePixi";
		}
	
		if (orientation == 'left' || orientation == 'right') {
			$('editTitleDiv').removeClassName("editTitle");
			$('editTitleDiv').addClassName(editTitleStyleWide);
			
			$('editContentDiv').removeClassName("editContent");
			$('editContentDiv').addClassName(editContentStyleWide);
			
			$('infoWrapperDiv').removeClassName("infoWrapper");
			$('infoWrapperDiv').addClassName(infoWrapperStyleWide);
			
			$('footerDiv').removeClassName("footer");
			$('footerDiv').addClassName(footerStyleWide);
		} else {
			$('editTitleDiv').removeClassName(editTitleStyleWide);
			$('editTitleDiv').addClassName("editTitle");
			
			$('editContentDiv').removeClassName(editContentStyleWide);
			$('editContentDiv').addClassName("editContent");
			
			$('infoWrapperDiv').removeClassName(infoWrapperStyleWide);
			$('infoWrapperDiv').addClassName("infoWrapper");
			
			$('footerDiv').removeClassName(footerStyleWide);
			$('footerDiv').addClassName("footer");
		}
	}
	
	
	// update title and content
	if (this.isNew) {
		$('editThoughtTitle').mojo.blur();
		$('editThoughtTitle').mojo.focus(); 
	} else {
		$('editThoughtTitle').mojo.blur();
		$('editThoughtTitle').mojo.focus(); 
		$('editThoughtTitle').mojo.blur();
	}
	
	this.setThoughtInfo(orientation);
	
	this.controller.modelChanged(this.thoughtTitleModel, this);
    this.controller.modelChanged(this.thoughtContentModel, this);
};

// ############## SQL functions ################

EditAssistant.prototype.updateThought = function(){
    try {
		this.thoughtContentModel.value = this.controller.get('editThoughtContent').innerHTML; 
		
        if (this.thoughtTitleModel.value.length > 0 || this.thoughtContentModel.value.length > 0) {
			
			if (this.selectedThought.content != this.thoughtContentModel.value || this.selectedThought.title != this.thoughtTitleModel.value) {
                // set changed data
                this.selectedThought.modified(this.thoughtTitleModel.value, this.thoughtContentModel.value);
				this.selectedThought.viewed();
				Mojo.Log.info("thought was modified and viewed");
			} else {
				this.selectedThought.viewed();
				Mojo.Log.info("thought was only viewed");
			}
            
			SortingThoughts.dao.updateThought(this.selectedThought);
			// update thought info
			var appController = Mojo.Controller.getAppController();
			var orientation = appController.getScreenOrientation();
			this.setThoughtInfo(orientation);
        } else {
			SortingThoughts.dao.deleteThought(this.selectedThought.id);
        }
        
    } catch (e) {
         Mojo.Log.error("Update Error: " + e);
    }
};

EditAssistant.prototype.selectThought = function(){

    if (!SortingThoughts.dao.db) {
        Mojo.Log.error("Could not access sorting thoughts database");
    } else {
        try {
			Mojo.Log.info("select thought");
            var sql = "SELECT content, rich FROM 'thought' WHERE ID = ?;";
            SortingThoughts.dao.db.transaction((function(transaction){
                transaction.executeSql(sql, [this.selectedThought.id], this.selectQueryDataHandler.bind(this), this.dbErrorHandler.bind(this));
            }).bind(this));
        } catch (e) {
            Mojo.Log.error("Sorting Thoughts DB Error: " + e);
        }
        
    }
};

EditAssistant.prototype.selectQueryDataHandler = function(transaction, results){
    try {
        for (var i = 0; i < results.rows.length; i++) {
            var row = results.rows.item(i);
            this.selectedThought.content = row['content'];
			var richFlag = row['rich'];
            
            //update widget
            this.thoughtTitleModel.value = this.selectedThought.title;
			var textWithLB = this.selectedThought.content;
			// replace line breaks only if thought created on palm
			if (!richFlag || richFlag != 1) {
				// workaround to keep line breaks alive in RichTextEdit 
				Mojo.Log.info("Replaced all line breks with rich breaks");
				textWithLB = textWithLB.replace(/(\r\n|\n|\r)/gm,"<br>");
			}
			this.controller.get('editThoughtContent').innerHTML = textWithLB;
            this.controller.modelChanged(this.thoughtTitleModel, this);
            this.controller.modelChanged(this.thoughtContentModel, this);
			
            break;
        }
        
    } catch (e) {
         Mojo.Log.error("Query Handler Error: " + e);
    }
};

EditAssistant.prototype.dbSuccessHandler = function(transaction){
    Mojo.Log.info("Successfully updated thought");
};

EditAssistant.prototype.dbErrorHandler = function(transaction, error){
    Mojo.Log.error("Sorting Thoughts DB Error: " + error.message);
    Mojo.Controller.errorDialog(error.message, this.controller.window);
};